 


using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Filter;
using CoreCms.Net.Loging;
using CoreCms.Net.IServices;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Utility.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using SqlSugar;
using CoreCms.Net.Auth.HttpContextUser;
using CoreCms.Net.Repository;
using CoreCms.Net.Services;
using System.Collections.Generic;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace CoreCms.Net.Web.WebApi.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OrderMeetingController : ControllerBase
    {
        private readonly IHttpContextUser _user;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ICoreShopOrderMeetingServices _coreshopordermeetingServices;
        private readonly ICoreShopOrderMeetingUserServices _coreShopOrderMeetingUserServices;
        private readonly IOrderMeetingInvitationCodeServices _orderMeetingInvitationCodeServices;
        private readonly ICoreShopOrderMeetingGoodsServices _coreShopOrderMeetingGoodsServices;
        private readonly ICoreCmsUserServices _coreCmsUserServices;
        private readonly IOrderMeetingBrandServices _orderMeetingBrandServices;
        private readonly ICoreCmsGoodsCategoryServices _coreCmsGoodsCategoryServices;
        /// <summary>
        /// 构造函数
        ///</summary>
        public OrderMeetingController(IHttpContextUser user, IWebHostEnvironment webHostEnvironment
                   , ICoreShopOrderMeetingServices coreshopordermeetingServices
               , ICoreShopOrderMeetingUserServices coreShopOrderMeetingUserServices
              , IOrderMeetingInvitationCodeServices orderMeetingInvitationCodeServices
            , ICoreCmsUserServices coreCmsUserServices
            , ICoreShopOrderMeetingGoodsServices coreShopOrderMeetingGoodsServices
            , IOrderMeetingBrandServices orderMeetingBrandServices
            , ICoreCmsGoodsCategoryServices coreCmsGoodsCategory
                   )
        {
            _user = user;
            _webHostEnvironment = webHostEnvironment;
            _coreshopordermeetingServices = coreshopordermeetingServices;
            _coreShopOrderMeetingUserServices = coreShopOrderMeetingUserServices;
            _orderMeetingInvitationCodeServices = orderMeetingInvitationCodeServices;
            _coreCmsUserServices = coreCmsUserServices;
            _coreShopOrderMeetingGoodsServices = coreShopOrderMeetingGoodsServices;
            _orderMeetingBrandServices=orderMeetingBrandServices;
            _coreCmsGoodsCategoryServices= coreCmsGoodsCategory;

    }

        #region 获取列表============================================================
        // POST: Api/coreshopordermeeting/GetPageList
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<WebApiCallBack> GetPageList()
        {
            var jm = new WebApiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<CoreShopOrderMeeting>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<CoreShopOrderMeeting, object>> orderEx = orderField switch
            {
                "id" => p => p.id,
                "name" => p => p.name,
                "startdatetime" => p => p.startdatetime,
                "enddatetime" => p => p.enddatetime,
                _ => p => p.id
            };

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选

            //编号 int
            var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
            //订货会名称 varchar
            var name = Request.Form["name"].FirstOrDefault();
            if (!string.IsNullOrEmpty(name))
            {
                where = where.And(p => p.name.Contains(name));
            }
            //开始时间 datetime
            var startdatetime = Request.Form["startdatetime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(startdatetime))
            {
                if (startdatetime.Contains("到"))
                {
                    var dts = startdatetime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.startdatetime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.startdatetime < dtEnd);
                }
                else
                {
                    var dt = startdatetime.ObjectToDate();
                    where = where.And(p => p.startdatetime > dt);
                }
            }
            //结束时间 datetime
            var enddatetime = Request.Form["enddatetime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(enddatetime))
            {
                if (enddatetime.Contains("到"))
                {
                    var dts = enddatetime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.enddatetime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.enddatetime < dtEnd);
                }
                else
                {
                    var dt = enddatetime.ObjectToDate();
                    where = where.And(p => p.enddatetime > dt);
                }
            }
            //获取数据
            var list = await _coreshopordermeetingServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.msg = "数据调用成功!";
            return jm;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<WebApiCallBack> GetAllList()
        {
            var jm = new WebApiCallBack();
      
         
            //获取数据
            var list = await _coreshopordermeetingServices.QueryAsync();
            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.msg = "数据调用成功!";
            return jm;
        }
        #endregion

        #region 首页数据============================================================
        // POST: Api/coreshopordermeeting/GetIndex
        /// <summary>
        /// 首页数据,返回一场热门订货会
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Description("首页数据")]
        public async Task<WebApiCallBack> GetIndex()
        {
            var jm = new WebApiCallBack();

            Expression<Func<CoreShopOrderMeeting, object>> orderEx = "id" switch
            {
                "id" => p => p.id,
                "name" => p => p.name,
                "startdatetime" => p => p.startdatetime,
                "enddatetime" => p => p.enddatetime,
                _ => p => p.id
            };

            var orderBy = "asc" switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };

            //获取数据
            var list = await _coreshopordermeetingServices.QueryPageAsync(m=>m.isHot==true, orderEx, orderBy, 0, 1, true);
            if (list.Count == 0)
            {
                jm.code =400;
                jm.msg = "查询失败";
                return jm;
            }
            var item = list.First();
            //查找产品列表
            var goodlist = await _coreShopOrderMeetingGoodsServices.QueryPageAsync(m=>m.meetingid==item.id,
               null , orderBy, 0, 10, true);

            //返回数据
            jm.data = new { 
             meetinginfo=item,
             list= goodlist
            };
            jm.code = 0;
            jm.msg = "数据调用成功!";
            jm.status = true;
            return jm;

        }
        #endregion

  

        
     

       
 
 

        #region 预览数据============================================================
        // POST: Api/coreshopordermeeting/GetDetails/10
        /// <summary>
        /// 预览数据 ,可用来查看是否权限
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        [Authorize]
        public async Task<WebApiCallBack> Get([FromBody] FMIntId entity)
        {
            var jm = new WebApiCallBack();

            var model =await _coreShopOrderMeetingUserServices.QueryIsAllow(entity.id, _user.ID);
            if (model != null)
            {
             
                jm.code = 0;
                jm.data = model;
                jm.msg = "获取成功";
                return jm;
            }
            else
            {
                var meeting = await _coreshopordermeetingServices.QueryByIdAsync(entity.id, false);
                meeting.isAllow = false;
                jm.code = 0;
                jm.data = meeting;
                jm.msg = "获取成功";
                return jm;
            }


         

          
        }
        ///// <summary>
        ///// 查看详情
        ///// </summary>
        ///// <param name="meetingid"></param>
        /////    <param name="code"></param>
        ///// <returns></returns>
        //[HttpGet]
        //[Description("预览数据")]
        //[Authorize]
        //public async Task<WebApiCallBack> GetDetails([FromBody] FMIntId entity)
        //{
        //    var jm = new WebApiCallBack();


        //    var meettinguser = await _coreShopOrderMeetingUserServices.QueryIsAllow(entity.id, _user.ID);
        //    if (meettinguser == null)
        //    {
        //        jm.code = 401;
        //        jm.msg = "没有订货会权限";
        //        return jm;
        //    }


        //    //查找产品列表
        //    var orderBy = "asc" switch
        //    {
        //        "asc" => OrderByType.Asc,
        //        "desc" => OrderByType.Desc,
        //        _ => OrderByType.Desc
        //    };

        //    var goodlist = await _coreShopOrderMeetingGoodsServices.QueryPageAsync(m => m.meetingid == meettinguser.id,
        //       null, orderBy, 0, 10, true);

        //    //返回数据
        //    jm.data = new
        //    {
        //        meetinginfo = meettinguser,
        //        list = goodlist
        //    };
        //    jm.code = 0;
        //    jm.count = goodlist.TotalCount;
        //    jm.msg = "数据调用成功!";
        //    return jm;

        //}




        // POST: Api/coreshopordermeeting/GetDetails/10
        /// <summary>
        /// 通过邀请码 
        /// </summary>
        /// <param name="meetingid"></param>
        ///    <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        [Description("通过邀请码预览数据")]
        [Authorize]
        public async Task<WebApiCallBack> GetDetails([FromQuery]string code, [FromQuery]int meetingid)
        {
            var jm = new WebApiCallBack();

            #region  通过用户表先来查询一次，
            var meettinguser = await _coreShopOrderMeetingUserServices.QueryIsAllow(meetingid, _user.ID);
            if (meettinguser != null)
            {
                jm.code = 0;
                jm.data = new { isAllow=true};
                jm.msg = "获取成功";
                return jm;
            }
            #endregion

            //邀请码表，
            var model = await _orderMeetingInvitationCodeServices.QueryPageAsync(m => m.code == code&& m.meetingid== meetingid && m.isUse==false);
            if (model.Count == 0) //用户表有，则更新
            {
               
                jm.code = 400;
                jm.msg = "邀请码不存在";
                jm.data = new { isAllow = false };
                return jm;
            }
            //获取用户
            var user = await _coreCmsUserServices.QueryByIdAsync( _user.ID, false);
            //更新邀请码，
            model.First().userid = _user.ID;
            model.First().isUse = true;
            model.First().usetime = DateTime.Now;
           await _orderMeetingInvitationCodeServices.UpdateAsync(model.First());

            //更新or添加用户
            await _coreShopOrderMeetingUserServices.InsertAsync(new CoreShopOrderMeetingUser()
            {
                meetingid = meetingid,
                userid = _user.ID,
                phone = user.mobile,
                addtime = DateTime.Now,
                fromType = code,
                isAllow = true,

            });
            //var meeting = await _coreshopordermeetingServices.QueryByIdAsync(meetingid, false);
           // meeting.isAllow = true;
            jm.data = new { isAllow = true };
            jm.code = 0;
            jm.msg = "获取成功";
            return jm;

        }


        [HttpGet]
        [Description("获取订货会关联品牌")]
        [Authorize]
        public async Task<WebApiCallBack> GetBrand([FromQuery] int meetingid)
        {
            var jm = new WebApiCallBack();

            Expression<Func<OrderMeetingBrand, object>> orderEx = "id" switch
            {
                "id" => p => p.id,
            
            };
            //获取数据
            var list = await _orderMeetingBrandServices.QueryPageAsync(m => m.meetingid==meetingid, orderEx, OrderByType.Asc, 1, 99, true);
            if (list.Count == 0)
            {
                jm.code = 400;
                jm.msg = "查询失败";
                return jm;
            }


            //返回数据
            jm.data = list;
            jm.code = 0;
      
            jm.msg = "数据调用成功!";
            return jm;
        }



        [HttpGet]
        [Description("获取订货会关联品牌")]
        //[Authorize]
        public async Task<WebApiCallBack> GetCategory([FromQuery] int meetingid)
        {
            var jm = new WebApiCallBack();




            //获取产品数据，提取分类id
            var list = await _coreShopOrderMeetingGoodsServices.QueryPageAsync(m => m.meetingid == meetingid, p => p.id, OrderByType.Asc,1,9999);
            var subgroup= list.GroupBy(m => m.goods.goodsCategoryId);
            //获取分类了表
            var categories = await _coreCmsGoodsCategoryServices.QueryListByClauseAsync(p => p.id>0, p => p.sort,
            OrderByType.Asc);
            //遍历获取子分类list
            List<CoreCmsGoodsCategory> catelist = new List<CoreCmsGoodsCategory>();
            foreach (var item in subgroup)
            {
                
                 catelist.Add(categories.Where(c => c.id == item.Key).First());

            }
            //子分类group
            var cargraop = catelist.GroupBy(m => m.parentId);
            List<CoreCmsGoodsCategory> group = new List<CoreCmsGoodsCategory>();

            foreach (var item2 in cargraop)
            {
                var keyitem = categories.Where(c => c.id == item2.Key).First();
                keyitem.subCategory= item2.ToList();

                group.Add(keyitem);

            }

            //返回数据
            jm.data = group;
            jm.code = 0;
        
            jm.msg = "数据调用成功!";
            return jm;
        }


     
        #endregion







    }



}
